<template xmlns:el-col="http://www.w3.org/1999/html">
    <section>
        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px; ">
            <el-form :inline="true" ref="filters" :model="filters" size="small">
                <el-form-item label="关键字" prop="full_name">
                    <el-input v-model="filters.title"></el-input>
                </el-form-item>

                <el-form-item label="是否发布" prop="show_status">
                    <el-select clearable v-model.Number="filters.show_status" clearable　placeholder="">
                        <el-option :key="txt" :label="txt" :value="val"
                                   v-for="(txt, val) in dict.news_status"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="searchUsers">搜索</el-button>
                    <el-button @click="resetSearch('filters')">重置</el-button>
                </el-form-item>

                <el-form-item style="display: block; float: right;">
                    <el-button type="primary" @click="handleAdd"><i class="el-icon-plus"></i> 添加</el-button>
                </el-form-item>
            </el-form>
        </el-col>


        <el-table :data="datas" style="width: 100%">
            <el-table-column label="序号" type="index" width="100"/>
            <el-table-column prop="title" label="标题"  />
            <el-table-column prop="gmt_created" width="200" label="创建日期" />
            <el-table-column
                    align="center"
                    label="发布状态"
                    width="100"
                    prop="notice_book_name">
                <template slot-scope="scope">
                    <span v-if="scope.row.show_status === '1'">已发布</span>
                    <span v-else>未发布</span>
                    <span></span>
                </template>
            </el-table-column>

            <el-table-column prop="file" width="100" label="附件" >
                <template slot-scope="scope">

                    <div v-if="scope.row.fileDocs.length>0" >
                        <a :href="base_url + scope.row.fileDocs[0].path" target="_blank" >
                            <i class="iconfont icon-huanzhebaogao"></i>
                        </a>
                    </div>

                </template>
             </el-table-column>

            <el-table-column label="操作" width="260">
                <template slot-scope="scope">
                    <el-button type="warning" v-if="scope.row.show_status === '1'" plain @click="handleCancel(scope.row)">撤销</el-button>
                    <el-button type="success" v-else plain @click="handlePublish(scope.row)">发布</el-button>
                    <el-button type="primary" plain @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button type="danger" plain @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>


        <!--工具条-->
        <el-col :span="24" class="toolbar">
            <!--分页-->
            <el-pagination
                    style="text-align: center;"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :page-size="pager.page_size"
                    :page-sizes="pager.sizes"
                    background
                    :current-page="pager.page_current"
                    layout="prev,pager,next,sizes,total"
                    :total="pager.total">
            </el-pagination>
        </el-col>

        <el-dialog :title="dialogTitle" v-loading="dialogLoading" :visible.sync="dialogVisible"
                   width="660px" :before-close="handleClose" top="30vh">
            <el-form :model="userInfo" :rules="userRules" ref="userInfo" label-width="100px" class="demo-fundProduct">
                <el-row>
                    <el-col :span="20" :push="1">
                        <el-input type="hidden" v-model="userInfo.id"></el-input>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="20" :push="1">
                        <el-form-item label="标题:" prop="title">
                            <el-input placeholder="标题" type="text" v-model="userInfo.title"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="20" :push="1">
                        <el-form-item label="链接地址:" prop="url">
                            <el-input placeholder="链接地址" type="text" v-model="userInfo.url"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="20" :push="1">
                        <el-form-item label="附件:" >
                            <el-upload
                                    class="upload-demo"
                                    action="/common/upload_file"
                                    :on-preview="handlePreview"
                                    :on-remove="handleRemove"
                                    :before-remove="beforeRemove"
                                    :on-change="handleChange"
                                    :on-success="handelSucces"

                                    :limit="2"
                                    :file-list="fileList">
                                <el-button size="small" type="primary">点击上传</el-button>

                            </el-upload>
                        </el-form-item>
                    </el-col>
                </el-row>





            </el-form>

            <el-row style="padding:30px 0">
                <el-col align="center">
                    <el-button type="primary" @click="submit">保 存
                    </el-button>
                    <el-button @click="handleClose">取 消</el-button>
                </el-col>
            </el-row>

        </el-dialog>

    </section>


</template>

<script>
    import * as api from '../../api/news_api.js';

    import dict  from '../../common/js/dict'
    import {userName, password, date_of_birth} from "../../common/js/checkFields";

    export default {
        data() {
            var validURL = (rule, value, callback) => {
                if (!rule.required && value === '') { callback() }
                let reg = /^((ht|f)tps?):\/\/([\w\-]+(\.[\w\-]+)*\/)*[\w\-]+(\.[\w\-]+)*\/?(\?([\w\-\.,@?^=%&:\/~\+#]*)+)?/;
                if (!reg.test(value)) {
                    callback(new Error('请输入正确的url链接地址'));
                } else {
                    callback();
                }
            };

            var validName = (rule, value, callback) => {
                let reg = /^[a-zA-Z\u4e00-\u9fa5]{1,10}$/;
                if (!reg.test(value)) {
                    callback(new Error('10位以内的汉字或字母'));
                } else {
                    callback();
                }
            };
            var validTelephone = (rule, value, callback) => {
                let reg = /^1[3|4|5|7|8][0-9]{9}$/;
                if (!reg.test(value)) {
                    callback(new Error('请输入正确的手机号码'));
                } else {
                    callback();
                }
            };
            var validPassword = (rule,value,callback) => {

                if(!/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/.test(value)){
                    callback(new Error("密码要求长度6-20位的字母与数字组合"));
                }else{
                    callback();
                }
            }
            return {
                dict: dict,
                //分页设置
                pager: {
                    sizes: [10, 20, 30, 40, 50],
                    total: 0,
                    page_size: 10,
                    page_current: 1
                },
                datas: [],
                roles: {},
                unitList: [],
                filters: {
                    title: '',
                    show_status: ''
                },
                fileList: []
                //dialog
                ,dialogVisible: false
                ,dialogLoading: false
                ,dialogTitle: '添加'
                ,userInfoBak:{}
                ,userInfo: {
                    id: '',
                    title: "",
                    url: "",
                    fileDocs:[],
                },
                base_url: this.$store.state.res_url
                ,userRules: {
                    UploadImage: [
                        {required: false, message: '', trigger: 'change'}
                    ],
                    title: [
                        {required: true, message: '请输入标题', trigger: 'blur'},

                    ],
                    url: [
                        {required: false, message: '请输入链接', trigger: 'blur'},
                        {validator: validURL, trigger: 'blur'}
                    ],

                }
            }
        },
        computed:{

        },
        created(){
            this.getList()
            this.userInfoBak=Object.assign({},this.userInfo)
        },
        methods: {
            handelSucces(res, file, fileList){
                this.userInfo.fileDocs = []
                this.userInfo.fileDocs.push(JSON.parse(res.datas))
            },
            handleChange(file, fileList) {

                this.fileList = fileList.slice(-1);
            },
            handleRemove(file, fileList) {
                this.userInfo.fileDocs = []
            },
            handlePreview(file) {
                console.log(file);
            },
            handleExceed(files, fileList) {
                this.$message.warning(`当前限制选择1个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
            },
            beforeRemove(file, fileList) {
                return this.$confirm(`确定移除 ${ file.name }？`);
            },
            //分页page_size发生改变
            handleSizeChange(val) {
                this.pager.page_current = 1;
                this.pager.page_size = val;
                this.getList();
            },
            //分页page_current发生改变
            handleCurrentChange(val) {
                this.pager.page_current = val;
                this.getList();
            },
            searchUsers() {
                this.pager.page_current = 1;
                this.getList();
            },
            resetSearch(formName){
                this.$refs[formName].resetFields();
                this.searchUsers();
            },
            getList() {

                let params = {
                    page_size: this.pager.page_size,
                    page_current: this.pager.page_current,
                    condition: this.filters
                };

                api.getList(params).then((res) => {
                    if (res.data.status === 200) {
                        let datas = JSON.parse(res.data.datas);
                        this.datas = datas.items;
                        this.pager.total = datas.total;
                    } else {
                        this.$message.error(res.data.status + " " + res.data.msg);
                    }

                });
            },


            // ========================================= add start ===============================================
            handleAdd() {
                this.dialogTitle = '添加';
                this.dialogVisible = true;

            },
            submit() {
                if (this.userInfo.url === '' && this.userInfo.fileDocs.length ===0){
                    this.$message.error("链接地址或附件不能为空");
                    return false
                }
                this.$refs['userInfo'].validate((valid) => {
                    if (valid) {
                        this.dialogLoading = true;  //显示loading
                        let params = this.userInfo
                        if(this.userInfo.id == ''){
                            api.onAdd(params).then((res) => {
                                this.dialogLoading = false;  //隐藏loading
                                if (res.data.status == 200) {
                                    this.$message({
                                        type: 'success',
                                        message: '添加成功!'
                                    });
                                    this.dialogVisible = false;
                                    this.searchUsers();
                                } else {
                                    if (res.data.status == 401) {
                                        this.$router.push('/login');
                                    }
                                    this.$message.error(res.data.msg);
                                    this.dialogVisible = false;
                                }
                            });
                        }else{
                            params.id = this.userInfo.id;
                            api.onUpdate(params).then((res) => {
                                this.dialogLoading = false;  //隐藏loading
                                if (res.data.status == 200) {
                                    this.$message({
                                        type: 'success',
                                        message: '编辑成功!'
                                    });
                                    this.dialogVisible = false;

                                    this.searchUsers();
                                } else {
                                    if (res.data.status == 401) {
                                        this.$router.push('/login');
                                    }
                                    this.$message.error(res.data.msg);
                                    this.dialogVisible = false;
                                }
                            });
                        }
                        this.handleClose();

                    }
                });
            },
            handleClose() {
                this.dialogVisible = false;
                this.userInfo = Object.assign({},this.userInfoBak)
                this.fileList = []

            },
            // ========================================= add end ===============================================
            // ========================================= edit start ===============================================
            handleEdit(row) {
               // this.userRules.content[0].required = false; //修改的时候密码可以为空
                this.dialogTitle = '编辑';
                this.dialogVisible = true;
                //this.dialogLoading = true;  //显示loading
                this.userInfo = Object.assign( this.userInfo ,row)
                if (row.fileDocs.length >0){
                    this.fileList = []
                    this.fileList.push({
                        name:row.fileDocs[0].originName,
                        url:row.fileDocs[0].path
                    })
                }

             //   let params = {"id": row.id};
               /* api.userInfo(params).then((res) => {
                    if (res.data.status === 200) {
                        this.dialogLoading = false;  //显示loading
                        this.userInfo = JSON.parse(res.data.datas);
                    } else {
                        this.$message({
                            type: 'info',
                            message: '系统繁忙'
                        });
                    }
                });*/
            },
            // ========================================= edit end ===============================================

            handleDelete(row) {
                this.$confirm('确认删除此条数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let params = {"id": row.id};
                   api.onDelete(params).then((res) => {
                        if (res.data.status === 200) {
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            this.getList();
                        } else {
                            this.$message({
                                type: 'info',
                                message: result.msg
                            });
                        }
                    });

                });
            },

            handlePublish(row) {
                console.log(row)
                let params = {"id": row.id};
                api.onPublish(params).then((res) => {
                    if (res.data.status === 200) {
                        this.$message({
                            type: 'success',
                            message: '操作成功!'
                        });
                        this.getList();
                    } else {
                        this.$message({
                            type: 'info',
                            message: result.msg
                        });
                    }
                });

            },

            handleCancel(row) {
                let params = {"id": row.id};
                api.onCancel(params).then((res) => {
                    if (res.data.status === 200) {
                        this.$message({
                            type: 'success',
                            message: '操作成功!'
                        });
                        this.getList();
                    } else {
                        this.$message({
                            type: 'info',
                            message: result.msg
                        });
                    }
                });

            }


        },


    }
</script>
<style>

</style>
